package com.twang.stock.service.jinyan;

import com.twang.stock.entity.CompanyCodeInfo;
import com.twang.stock.entity.StockInfo;
import com.twang.stock.entity.StockInfoDto;
import com.twang.stock.mapper.CompanyCodeInfoMapper;
import com.twang.stock.mapper.StockInfoMapper;
import com.twang.stock.service.impl.MinutesVolRuleService;
import com.twang.stock.threadPool.AsycTaskExecutorConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 更新5日、10日、20日的价格和成交量
 */
@Service
@Slf4j
public class UpdtePriceAndVolService {

    @Resource
    private CompanyCodeInfoMapper companyCodeInfoMapper;
    @Resource
    private StockInfoMapper stockInfoMapper;

    @Autowired
    private AsycTaskExecutorConfig asycTaskExecutorConfig;

    @Autowired
    private MinutesVolRuleService minutesVolRuleService;

    public void updtePriceAndVol() {
        List<CompanyCodeInfo> stockList = companyCodeInfoMapper.selectAll();
        stockList.forEach(item -> {
            asycTaskExecutorConfig.taskQueueExecutor().execute(() -> {
                execute(item);
                log.info("{} 更新 MAY5、MAY10 end!",item.getShortName());
            });
        });
    }

    /**
     * 计算涨跌
     */
    public void updateZhangDie(){
        List<CompanyCodeInfo> stockList = companyCodeInfoMapper.selectAll();
        stockList.forEach(item -> {
            asycTaskExecutorConfig.taskQueueExecutor().execute(() -> {
                StockInfo param=new StockInfo();
                param.setCode(item.getCompanyCode());
                List<StockInfo> infoList=stockInfoMapper.select(param);
                infoList.forEach(info->{
                    try{
                        asycTaskExecutorConfig.taskQueueExecutor().execute(() ->updateHznagDie(info));
                    }catch (Exception e){
                        log.error("更新异常，code={} name={} e={}",item.getCompanyCode(),item.getShortName(),e);
                    }
                });

            });
        });
    }

    private void execute(CompanyCodeInfo item){
        try {
            Example example = new Example(StockInfo.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("code", item.getCompanyCode());
            criteria.andIsNull("priceMay5");
            example.orderBy("date").desc();
            List<StockInfo> itemList = stockInfoMapper.selectByExample(example);
            itemList.forEach(data -> {
                //5日
                updatePriceAndVol(data, 5);
                //10
                updatePriceAndVol(data, 10);
                stockInfoMapper.updateByPrimaryKey(data);
            });
        } catch (Exception e) {
            log.info(" 更新 MAY5、MAY10 异常 e={}", e);
        }
    }


    private void updateHznagDie(StockInfo item) {
        //上一交易日
        StockInfo stockInfoYesterDay = minutesVolRuleService.getCode(item.getCode(), item.getDate());
        if (null == stockInfoYesterDay) {
            return;
        }
        item.setZhangdie(((item.getPrice().subtract(stockInfoYesterDay.getPrice())).divide(stockInfoYesterDay.getPrice(), 5, BigDecimal.ROUND_HALF_UP)).multiply(new BigDecimal(100)));
        stockInfoMapper.updateByPrimaryKey(item);
        updateHznagDie(stockInfoYesterDay);
    }


    public void updatePriceAndVol(StockInfo item, int day) {
        StockInfoDto param = new StockInfoDto();
        param.setCode(item.getCode());
        param.setDate(item.getDate());
        param.setNum(day - 1);
        if (day == 5) {
            item.setPriceMay5(new BigDecimal(0));
            item.setVolMay5(0);
        }
        if (day == 10) {
            item.setPriceMay10(new BigDecimal(0));
            item.setVolMay10(0);
        }
        //更新MAY-5
        List<StockInfo> listMay = stockInfoMapper.updateSUMVolAndAmountNew(param);
        BigDecimal priceMay5 = BigDecimal.ZERO;
        BigDecimal priceMay10 = BigDecimal.ZERO;
        Integer volMay5 = 0;
        Integer volMay10 = 0;
        for (StockInfo may : listMay) {
            if (day == 5) {
                priceMay5 = priceMay5.add(may.getPrice());
                volMay5 = volMay5 + may.getVolMay1();
            }
            if (day == 10) {
                priceMay10 = priceMay10.add(may.getPrice());
                volMay10 = volMay10 + may.getVolMay1();
            }
        }
        if (day == 5) {
            item.setPriceMay5(priceMay5.add(item.getPrice()).divide(new BigDecimal(day), 2, BigDecimal.ROUND_HALF_UP));
            item.setVolMay5((volMay5 + item.getVolMay1()) / day);
        }
        if (day == 10) {
            item.setPriceMay10(priceMay10.add(item.getPrice()).divide(new BigDecimal(day), 2, BigDecimal.ROUND_HALF_UP));
            item.setVolMay10((volMay10 + item.getVolMay1()) / day);
        }
    }



}
